<template>
	<view>
		<view class="edgeInsetTop"></view>
		<div class="" style="padding:15px;">
			<span class="sel-lable" :class="{'active':receipt_type=='个人'}" tapmode @click="receipt_type='个人'">个人</span>
			<span class="sel-lable" :class="{'active':receipt_type=='单位'}" tapmode @click="receipt_type='单位'">单位</span>
		</div>
		<view class="cu-form-group">
			<view class="title">发票抬头</view>
			<input type="text" placeholder="请输入发票抬头" v-model="receipt_person"></input>
		</view>
		<block v-if="receipt_type=='个人'">
			<view class="cu-form-group">
				<view class="title">手机号</view>
				<input type="number" placeholder="请输入手机号" maxlength="11" v-model="receipt_phone"></input>
			</view>
			<view class="cu-form-group">
				<view class="title">邮箱</view>
				<input type="text" placeholder="请输入邮箱" v-model="receipt_email"></input>
			</view>
		</block>
		<block v-if="receipt_type=='单位'">
			<view class="cu-form-group">
				<view class="title">税号</view>
				<input type="text" placeholder="请输入税号" v-model="receipt_num"></input>
			</view>
			<view class="cu-form-group">
				<view class="title">开户银行</view>
				<input type="text" placeholder="请输入开户银行" v-model="receipt_bank"></input>
			</view>
			<view class="cu-form-group area">
				<view class="click" @tap="btnClick"></view>
				<view class="title">开户地区</view>
				<input type="text" :value="receipt_address" placeholder="请选择开户地区" disabled />
			</view>
			<view class="cu-form-group">
				<view class="title">银行账号</view>
				<input type="text" placeholder="请输入银行账号" v-model="receipt_account"></input>
			</view>
			<view class="cu-form-group">
				<view class="title">营业地址</view>
				<input type="text" placeholder="请输入营业地址" v-model="business_address"></input>
			</view>
			<view class="cu-form-group">
				<view class="title">营业电话</view>
				<input type="text" placeholder="请输入营业电话" v-model="business_phone"></input>
			</view>
			<view class="cu-form-group margin-top-bj">
				<view class="title">增值税专用发票</view>
				<switch @change="switchChange" :class="ticket_type == 1?'checked':''" :checked="ticket_type == 1">
				</switch>
			</view>
		</block>
		<!-- 1.0.5升级 -->
		<!-- 1.0.6升级 -->
		<view class="padding-bj flex flex-direction margin-top">
			<button @tap="confirm" class="cu-btn wanl-bg-orange lg">完成</button>
		</view>
		<wanl-address ref='wanlAddress' @selectAddress="successSelectAddress"></wanl-address>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				receipt_person: '',
				receipt_type: '单位',
				receipt_name: '',
				receipt_num: '',
				receipt_phone: '',
				receipt_email: '',
				receipt_address: '',
				receipt_account: '',
				receipt_bank: '',
				is_default: 0,
				province_id: 0,
				province_name: '',
				city_id: 0,
				city_name: '',
				area_id: 0,
				area_name: '',
				ticket_type: 0,
				business_address: '',
				business_phone: '',
				id: 0
			}
		},
		onLoad(option) {
			let title = '新增发票 ';
			if (option.type === 'newadd') {
				this.is_default = 1
			}
			if (option.type === 'edit') {
				title = '编辑发票'
				let data = JSON.parse(option.data)
				// 1.1.6 升级
				this.receipt_person = data.person
				this.receipt_type = data.type
				this.receipt_account = data.account
				this.receipt_bank = data.bank
				this.receipt_address = data.address
				this.receipt_phone = data.phone
				this.receipt_email = data.email
				this.province_id = data.province_id
				this.province_name = data.province_name
				this.city_id = data.city_id
				this.city_name = data.city_name
				this.area_id = data.area_id
				this.area_name = data.area_name
				this.is_default = data.is_default
				this.ticket_type = data.ticket_type
				this.receipt_num = data.num
				this.business_address = data.business_address
				this.business_phone = data.business_phone
			}
			this.manageType = option.type;
			this.$wanlshop.title(title);
		},
		onNavigationBarButtonTap() {
			this.confirm()
		},
		methods: {
			isGetLocation(a = "scope.userLocation") { //检查当前是否已经授权访问scope属性
				var _this = this;
				uni.getSetting({
					success(res) {
						console.log(res)
						if (!res.authSetting[a]) { //每次进入程序判断当前是否获得授权，如果没有就去获得授权，如果获得授权，就直接获取当前地理位置
							_this.getAuthorizeInfo()
						} else {
							//方式一
							_this.getLocationInfo();
							// 方式二
							// _this.getLocation();
						}
					}
				});
			},
			getAuthorizeInfo(a = "scope.userLocation") { // uniapp弹窗弹出获取授权（地理，个人微信信息等授权信息）弹窗
				var _this = this;
				uni.authorize({
					scope: a,
					success() { //允许授权
						//方式一
						// _this.getLocationInfo();
						// 方式二
						_this.getLocation();
					}
				})
			},
			//点击地图时
			clickMap(e) {
				console.log("点击地图时:" + e);
				this.latitude = e.detail.latitude;
				this.longitude = e.detail.longitude;
			},
			getLocationInfo() {
				//直接调用即可
				uni.chooseLocation({
					success: (res) => {
						console.log(res)
						if (res.errMsg == "chooseLocation:ok") {
							this.address_info = res.name + res.address;
							this.latitude = res.latitude;
							this.longitude = res.longitude;
						}
					}
				})
			},
			//获取当前所在位置的经纬度
			getLocation() {
				// #ifdef MP
				uni.getFuzzyLocation({
					type: 'wgs84',
					success: (res) => {
						console.log(res)
						this.latitude = res.latitude.toString()
						this.longitude = res.longitude.toString()

						// 获取地理位置详情信息
						this.getLocationDetail()
					}
				});
				// #endif
				
				// #ifdef APP-PLUS
				uni.getLocation({
					type: 'wgs84',
				    success: (res) => {
				        console.log(res)
				        this.latitude = res.latitude.toString()
				        this.longitude = res.longitude.toString()
				                        
				        // 获取地理位置详情信息
				        this.getLocationDetail()
				    }
				});
				// #endif
			},
			//根据经纬度获取详细的地址
			getLocationDetail() {
				uni.request({
					header: {
						"Content-Type": "application/text"
					},
					url: 'https://apis.map.qq.com/ws/geocoder/v1/?location=' + this.latitude + ',' + this
						.longitude +
						'&key=W4DBZ-C4LLD-4BK4C-P74JB-5YTCO-YLB3C',
					success: (re) => {
						//成功获取到经纬度
						console.log(re)
						if (re.statusCode == 200) {
							this.address_info_recomd = re.data.result.formatted_addresses.recommend
							this.address_info = re.data.result.address_reference.town.title + re.data.result
								.address_reference.street.title + re.data.result.address_reference.landmark_l2
								.title
							this.address = re.data.result.address
							// this.saveAddress()
						} else {
							uni.showToast({
								title: '获取地理位置失败，请重试',
								icon: "none"
							})
						}
					}
				});
			},
			// 在地图渲染更新完成时触发
			regionchange(e) {
				console.log(e)
				if (e.type == 'end' && (e.causedBy == 'scale' || e.causedBy == 'drag')) {
					this.mapCtx = uni.createMapContext("mapSelected"); // 创建map的上下文对象, 从而操控map组件
					this.mapCtx.getCenterLocation({
						success: (res) => {
							console.log(res)
							this.latitude = res.latitude;
							this.longitude = res.longitude;
							this.getLocationDetail();
						}
					})
				}
			},
			getLocal(success) {
				//APP端使用
				console.log(777)
				uni.getLocation({
					type: 'gcj02',
					geocode: true,
					success: function(re) {
						console.log(888)
						uni.chooseLocation({
							latitude: re.latitude,
							longitude: re.longitude,
							success: function(resp) {
								/**
								 * 逆地理编码
								 * 参考 https://lbs.amap.com/api/webservice/guide/api/georegeo
								 */
								uni.request({
									url: "https://restapi.amap.com/v3/geocode/regeo",
									method: 'get',
									data: {
										location: resp.longitude + "," + resp
											.latitude, //位置坐标:格式：location=lng<经度>,lat<纬度>
										key: '1e8aba34389a21d169d1d0495106ef09', //开发密钥（web服务Key）
										radius: 0,
										extensions: 'all', //base，返回基本地址信息；all 时会返回基本地址信息、附近 POI 内容、道路信息以及道路交叉口信息
										batch: false,
										roadlevel: 1
									},
									success: function(res) {
										console.log(res, '====');
										const data = res.data.regeocode;
										const province = data.addressComponent
											.province; //省
										const city = data.addressComponent.city; //市
										const district = data.addressComponent
											.district; //区
										const township = data.addressComponent
											.township; //街道
										const address = township + data?.pois[0]
											?.name + data?.pois[0]?.address;
										const reasult = {
											province,
											city,
											district,
											address,
										}
										success(reasult);
									},
									error: function(err) {
										uni.$u.toast("服务端错误，请重试");
									}

								})
							},
							fail(err) {
								uni.$u.toast("已取消");
								console.log(err, 'err');
							},
						});
					}
				});
			},
			switchChange(e) {
				if (e.detail.value) {
					this.ticket_type = 1;
				} else {
					this.ticket_type = 0;
				}
			},
			btnClick() {
				this.$refs.wanlAddress.show()
			},
			successSelectAddress(address) {
				// this.addressData.country = address.country;
				// this.addressData.province_name = address.province;
				// this.addressData.city_name = address.city;
				// this.addressData.citycode = address.citycode;
				// this.addressData.area_name = address.district;
				// this.city_id =  address.city
				this.province_name = address.province;
				this.city_name = address.city;
				// this.area_id= this.area_id,
				this.area_name = address.district;
				this.receipt_address = address.formatted_address;

			},
			//调用高德地图搜索相关地址
			getInputtips(event) {
				let keywords = event.detail.value;
				if (keywords) {
					uni.request({
						url: 'https://restapi.amap.com/v3/assistant/inputtips',
						data: {
							key: '1e8aba34389a21d169d1d0495106ef09',
							keywords: keywords,
							location: this.addressList.location,
							city: this.addressList.adcode
						},
						success: (res) => {
							let addressList = [];
							// 1.1.7升级
							if (res.res.infocode == 10001) {
								this.$wanlshop.msg('后台未配置高德地图KEY，不支持联想，完成编辑后点击空白展开全部');
							} else {
								res.res.tips.forEach(item => {
									if (item.address.length == 0) {
										item.address = '暂未收录地址';
										item.location = '113.294701,22.666562';
									}
									addressList.push(item);
								});
							}
							this.addressList.tips = addressList;
						}
					});
				}
			},
			// 详细地址失去焦点
			blurInputtips(event) {
				this.addressData.address = event.detail.value;
				setTimeout(() => {
					this.addressType = true;
				}, 10);
			},
			// 详细地址已完成
			confirmInputtips(event) {
				this.addressType = true;
			},
			// 详细地址获取焦点
			focusInputtips(event) {
				this.addressType = false;
			},
			// 详细地址替换
			addressTisp(data) {
				this.addressData.adcode = data.adcode;
				this.addressData.address = data.address;
				this.addressData.address_name = data.name;
				// 1.0.5升级
				if (data.address) {
					this.addressData.detailed_address = this.addressData.address_name + this.addressData.address;
				}
				this.addressData.location = data.location;
				this.addressType = true;
			},
			//提交
			confirm() {
				// let data = this.addressData;
				// alert(JSON.stringify(data))
				if (!this.receipt_person) {
					this.$wanlshop.msg('请填写发票抬头');
					return;
				}
				// if (!/^1[0-9]{10,10}$/.test(data.receipt_phone)) { // 1.0.2升级
				// 	this.$wanlshop.msg('请输入正确的手机号码');
				// 	return;
				// }
				// if (!data.city) {
				// 	this.$wanlshop.msg('请选择地区');
				// 	return;
				// }
				// if (!data.address) {
				// 	this.$wanlshop.msg('请填写详细信息');
				// 	return;
				// }
				let data = {
					id: this.id,
					receipt_type: this.receipt_type,
					receipt_account: this.receipt_account,
					receipt_bank: this.receipt_bank,
					receipt_person: this.receipt_person,
					receipt_address: this.receipt_address,
					receipt_phone: this.receipt_phone,
					receipt_email: this.receipt_email,
					province_id: this.province_id,
					province_name: this.province_name,
					city_id: this.city_id,
					city_name: this.city_name,
					area_id: this.area_id,
					area_name: this.area_name,
					is_default: this.is_default,
					ticket_type: this.ticket_type,
					receipt_num: this.receipt_num,
					business_address: this.business_address,
					business_phone: this.business_phone,
				}
				this.$wanlshop.prePage().refreshList(data, this.manageType);
				this.$wanlshop.msg(`地址${this.manageType=='edit' ? '修改': '添加'}成功`);
				this.$wanlshop.back(1);
			}
		}
	}
</script>

<style>
	.sel-lable {
		display: inline-block;
		width: 3.5rem;
		text-align: center;
		height: 1.5rem;
		border-radius: .75rem;
		font-size: .7rem;
		font-family: PingFangSC-Regular;
		font-weight: 400;
		color: rgba(51, 51, 51, 1);
		line-height: 1.5rem;
		background: rgba(238, 238, 238, 1);
		margin-right: 0.5rem;
	}

	.sel-lable.active {
		color: #fff;
		background: #005A93
	}

	.cu-form-group {
		padding: 0 25rpx;
	}

	/* 1.1.5升级 */
	.cu-form-group.area {
		position: relative;
	}

	.cu-form-group.area .click {
		position: absolute;
		z-index: 99;
		right: 0;
		left: 0;
		top: 0;
		bottom: 0;
	}

	.cu-form-group .title {
		min-width: calc(4em + 15px);
		font-size: 26rpx;
	}

	.cu-form-group input,
	.cu-form-group textarea {
		font-size: 26rpx;
	}

	.cu-btn.lg {
		font-size: 32rpx;
		height: 86rpx;
	}

	.tipsScroll {
		width: 100%;
		height: 500rpx;
		padding: 0 50rpx;
	}

	.tipsScroll .item {
		margin: 25rpx 0;
	}

	.tipsScroll .item view {
		color: #B8B8B8;
		font-size: 22rpx;
	}

	.tipsScroll .item text {
		color: #333;
	}
</style>